﻿using System;
using System.Collections.Generic;
using System.Threading;
using ThrottledProcessing.SampleApplication.Domain;
using ThrottledProcessing.SampleApplication.Interfaces;
using ThrottledProcessing.SampleApplication.Messages;

namespace ThrottledProcessing.SampleApplication.Services
{
    public class SearchService : ISearchService
    {
        private readonly ILoggingService loggingService;

        public SearchService(ILoggingService loggingService)
        {
            this.loggingService = loggingService;
        }

        public SearchResponse Search(SearchRequest request)
        {
            // Simulate latency
            Thread.Sleep(DateTime.Now.Millisecond*2);

            // Simulate exceptions
            if (DateTime.Now.Second < 20)
                throw new Exception("Simulated exception thrown from search service!");

            loggingService.Debug(string.Format("Searching for keyword: {0}", request.Query.Keyword));
            var query = request.Query;
            var items = new List<ContentItem>();
            var startIndex = query.Page*query.ResultsPerPage;
            var endIndex = startIndex + query.ResultsPerPage;
            for (var i = startIndex; i < endIndex; i++)
            {
                items.Add(new ContentItem
                              {
                                  Title = string.Format("Title {0} {1}", query.Keyword, i),
                                  Description = string.Format("Description of content item {0} {1}", query.Keyword, i),
                                  Url =
                                      string.Format("http://wwww.{0}.com/{1}/{2}/{3}", query.Keyword, DateTime.Now.Hour,
                                                    DateTime.Now.Minute, i)
                              });
            }
            return new SearchResponse
                       {
                           Items = items
                       };
        }
    }
}